// 封装axios
import axios from "axios";
import { getToken,clearToken } from "@/utils/token";
import { Toast } from "@ant-design/react-native";
import { tansParams } from "@/utils/ruoyi";
import JSONbig from "json-bigint";
import { router } from "expo-router";
// import { Logout } from "@/redux/slices/login";

// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

const service = axios.create({
  baseURL: "https://www.u685636.nyat.app:43610",
  timeout: 10000,
  transformResponse: [
    (data) => {
      // 将返回对象进行重写,防止精度丢失
      const json = JSONbig({
        storeAsString: true,
      });
      return json.parse(data);
    },
  ],
});
// 添加请求拦截器
service.interceptors.request.use(
  async (config) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
    const token = await getToken()
    if (token && !isToken) {
      // 每一个请求头都带上token
      config.headers["Authentication"] = token;
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (
      !isRepeatSubmit &&
      (config.method === "post" || config.method === "put")
    ) {
      const requestObj = {
        url: config.url,
        data:
          typeof config.data === "object"
            ? JSON.stringify(config.data)
            : config.data,
        time: new Date().getTime(),
      };
      const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
      const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
      if (requestSize >= limitSize) {
        console.warn(
          `[${config.url}]: ` +
            "请求数据大小超出允许的5M限制，无法进行防重复提交验证。"
        );
        return config;
      }
    }
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (res) => {
    // const dispatch = useDispatch();
    // 未设置状态码则默认成功状态
    const code = res.data.code || "20000";
    // 获取错误信息
    const msg = res.data.msg || "请求异常";
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }
    // tiken不存在未登录
    if (
      code === "A0001" ||
      code === "A0002" ||
      code === "A0003" ||
      code === "A0004" ||
      code === "A0005"
    ) {
      Toast.fail("请重新登录");
      // 跳转到登录页（当前页面会被替换）
      clearToken();
      router.replace("/login");
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code !== "20000") {
      Toast.offline(msg);
      return Promise.reject("error");
    } else {
      return res.data;
    }
  },
  (error) => {
    console.log("err", error);
    let msg = error.message;
    if (msg == "Network Error") {
      msg = "后端接口连接异常";
    } else if (msg.includes("timeout")) {
      msg = "系统接口请求超时";
    } else if (msg.includes("Request failed with status code")) {
      msg = "系统接口" + msg.substr(msg.length - 3) + "异常";
    }
    Toast.offline(msg);
    return Promise.reject(error);
  }
);

export default service;
